<template>
    <div class="login-container">
        <h2>登录</h2>
        <form @submit.prevent="handleLogin">
            <div class="form-group">
                <label for="username">用户名：</label>
                <input type="text" id="username" v-model="username" required>
            </div>
            <div class="form-group">
                <label for="password">密码：</label>
                <input type="password" id="password" v-model="password" required>
            </div>
            <button type="submit">登录</button>
            <div v-if="error" class="error">{{ error }}</div>
        </form>
    </div>
</template>

<script>

import axios from 'axios';

export default {
    data() {
        return {
            username: '',
            password: '',
            error: ''
        };
    },
    methods: {
        async handleLogin() {
            try {
                const response = await axios.post(`${cross.env.url}/login`, {
                    username: this.username,
                    password: this.password
                });

                console.log('登录响应数据:', response.data);
                if (response.data.success) {
                    this.setCookie(response.data.token);
                    this.$router.push('/dashboard'); // 登录成功后跳转到仪表盘页面
                    this.error = '登录成功';
                } else {
                    this.error = data.error;
                }
            } catch (error) {
                this.error = '登录请求失败，请稍后再试';
                console.error('登录请求失败:', error);
            }
        },
        setCookie(token) {
            document.cookie = token;
        }
    }
};
</script>

<style scoped>
.login-container {
    width: 300px;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    display: flex;
    /* 添加 */
    flex-direction: column;
    /* 添加 */
    justify-content: center;
    /* 添加 */
    align-items: center;
    /* 添加 */
    position: fixed;
    /* 添加 */
    top: 50%;
    /* 添加 */
    left: 50%;
    /* 添加 */
    transform: translate(-50%, -50%);
    /* 添加 */
}

.form-group {
    margin-bottom: 15px;
}

label {
    display: block;
    margin-bottom: 5px;
}

input {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
}

button {
    width: 100%;
    padding: 10px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background-color: #0056b3;
}

.error {
    color: red;
    text-align: center;
}
</style>